package com.rocching.easychat.util;

import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.model.AppConst;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HttpUtil {
    private final static String TAG = HttpUtil.class.getName();
    public static final MediaType jsonMediaType = MediaType.get("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient();
    private static final String authorizationKey = "Authorization";
    private static final String bearerKey = "Bearer";
    private static String bearerValue = "";

    public static void setBearerValue(String value) {
        bearerValue = value;
    }

    public static <T> void get(String url, IApiCallback<T> callback, Class<T> tClass) {
        get(url, null, callback, tClass);
    }

    public static <T> void get(String url, Map<String, Object> map, IApiCallback<T> callback, Class<T> tClass) {
        Request request = getBuilder(url, map).build();
        request(request, callback, tClass);
    }

    public static <T> void post(String url, Object data, IApiCallback<T> callback, Class<T> tClass) {
        String bodyString = "";
        if (!Objects.isNull(data)) {
            bodyString = JsonUtil.toJson(data);
        }

        RequestBody body = RequestBody.create(bodyString, jsonMediaType);
        Request request = getBuilder(url, null).post(body).build();
        request(request, callback, tClass);
    }

    public static <T> void put(String url, Object data, IApiCallback<T> callback, Class<T> tClass) {
        RequestBody body = RequestBody.create(Objects.requireNonNull(JsonUtil.toJson(data)), jsonMediaType);
        Request request = getBuilder(url, null).put(body).build();
        request(request, callback, tClass);
    }

    public static <T> void uploadFile(String url, RequestBody body, IApiCallback<T> callback, Class<T> tClass) {
        Request request = getBuilder(url, null).post(body).build();
        request(request, callback, tClass);
    }

    private static <T> void request(Request request, IApiCallback<T> callback, Class<T> tClass) {
        try {
            Log.i(TAG, "the request url is:" + request.url());
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    if (callback != null) {
                        ResponseBody body = response.body();
                        String error = "网络错误,请求失败";
                        if (body != null) {
                            String content = body.string();
                            JSONObject jsonObject = JsonUtil.parseObject(content);
                            Log.i(TAG, "the body is:" + content);
                            if (jsonObject != null) {
                                Integer statusCode = jsonObject.getInteger("StatusCode");
                                if (Objects.isNull(statusCode)) {
                                    statusCode = 0;
                                }
                                if (statusCode == 200) {
                                    if (tClass.equals(Object.class)) {
                                        callback.onResponse(true, content, null);
                                    } else {
                                        callback.onResponse(true, content, jsonObject.getObject("Data", tClass));
                                    }
                                    return;
                                } else {
                                    error = jsonObject.getString("Errors");
                                }
                            }
                        }
                        callback.onResponse(false, error, null);
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    private static Request.Builder getBuilder(String url, Map<String, Object> map) {
        Request.Builder builder = new Request.Builder().url(getRequestUrl(url, map));
        if (!StringUtil.isEmpty(bearerValue)) {
            builder = builder.addHeader(authorizationKey, String.format("%s %s", bearerKey, bearerValue));
        }
        return builder;
    }

    private static String getRequestUrl(String url, Map<String, Object> map) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(AppConst.API_URL);
        if (!url.startsWith("/")) {
            stringBuilder.append("/");
        }
        stringBuilder.append(url);
        if (map != null && map.size() > 0) {
            int index = 0;
            stringBuilder.append("?");
            for (String key : map.keySet()) {
                stringBuilder.append(key).append("=").append(map.get(key));
                if (index < map.size() - 1) {
                    stringBuilder.append("&");
                }
                index++;
            }
        }
        return stringBuilder.toString();
    }
}
